/**
 * Created by hylin on  2014/7/16.
 * 我的车辆列表页面
 */

var deviceListPage = function(){
    var account = '',
        params = goome.wx.utils.defaultParams(),
        data = [],
        groupData = {},//按分组存放的数据
        listUrl = 'account/devinfo',//该接口获取设备列表基本信息
        realtimeUrl = 'account/monitor',//该接口获取设备即时信息
        $toolbar = $('.toolbar'),
        $deviceList = $('#device-list');

    function loadData(url){
        $.when(getRemoteData(listUrl), getRemoteData(realtimeUrl))
            .done(function(results1, results2){
                results1 = results1[0];
                results2 = results2[0];
                if(results1.errcode === 0 && results2.errcode === 0){
                    //将接口的数据进行整合，分组
                    convertList(results1.data, results2.data);
                    renderList();
                }else{
                    if(results1.errcode != 0) {
                        goome.wx.utils.showTip(results1);
                    }else{
                        goome.wx.utils.showTip(results2);
                    }
                }
            });
    }

    function getRemoteData(url){
        return $.ajax({
            url: goome.wx.config.apiUrl+url,
            data: params,
            dataType: 'jsonp',
            success: function(results){

            },
            error: function(err){
                goome.wx.utils.showTip(err);
            }
        });
    }

    function convertList(list, realtime){
        groupData = {};
        $.each(list, function(i,v){
            if(!groupData[v.group_id]){
                groupData[v.group_id] = [];
            }
            if(v.group_id == 0){
                v.group_name = wxLang.defaultGroup;
            }
            groupData[v.group_id].push(v);
            $.each(realtime, function(j, o){
                if(v.imei == o.imei){
                    $.each(o, function(k, p){
                        v[k] = p;
                    });
                    return false;
                }
            });
        });
    }

    function renderList(){
        var html = ['<dl>'];
        $.each(groupData, function(i, v){
            html.push('<dt data-group-id="'+(''+v[0].group_id || '')+'">'+ (v[0].group_name||'')+'<i class="icon-up"></i></dt>');
            $.each(v, function(j, p){
                html.push('<dd class="clearfix" data-group="'+ p.group_id+'" data-status="'+ p.device_info_new+'">');
                //未上线和过期的没有更多功能开放
                if(p.device_info_new == 0 || p.device_info_new == 3 || p.device_info_new == 4){
                    html.push('<div class="toggle-btn"></div>');
                }
                html.push('<div class="device-icon device-icon-'+p.device_info_new+'"></div><div class="info"><span class="device-name">'+ p.name+'</span><br/><span class="addons">[<span>'+goome.wx.config.status[p.device_info_new]+'</span>]&nbsp;<span class="device-number">'+ p.number+'</span></span></div>');
                html.push('<div class="toolbar"><a target="_self" href="track.html?'+goome.wx.utils.serialize()+'&imei='+ p.imei+'&name='+encodeURIComponent(p.name)+'&devtype='+ p.dev_type+'">'+wxLang.tracking+'</a><a target="_self" href="playback.html?'+goome.wx.utils.serialize()+'&imei='+ p.imei+'">'+wxLang.playback+'</a><a target="_self" href="info.html?'+goome.wx.utils.serialize()+'&imei='+ p.imei+'&lng='+ p.lng+'&lat='+ p.lat+'">'+wxLang.info+'</a></div>');
                html.push('</dd>');
            });
        });
        html.push('</dl>');
        $deviceList.html(html.join(''));
        deviceFilter($toolbar.find('input[name="filter-radio"]:checked').data('action'));
    }
    //按照在线、离线过滤显示列表
    function deviceFilter(type){
        if(type == 'all'){
            $deviceList.find('dd').show().data('filtered',false);
        }else {
            $.each($deviceList.find('dd'), function(i, v){
                var $this = $(this),
                    status = $this.data('status');
                if (type == 'online') {
                    if(status == '0' || status == '4'){
                        $this.show().data('filtered',false);
                    }else{
                        $this.hide().data('filtered',true);
                    }
                }else if (type == 'offline') {
                    if(status == '1' || status == '2' || status == '3'){
                        $this.show().data('filtered',false);
                    }else{
                        $this.hide().data('filtered',true);
                    }
                }
            });

        }
    }
    function bindEvents(){
        $deviceList.on('click', 'dt,dd', function(e){
            var $this = $(this),
                tagName = this.tagName.toUpperCase();
            if(tagName == 'DT'){
                var groupId = $this.data('group-id');
                $this.find('i').toggleClass('icon-down');
                $($.grep($deviceList.find('dd[data-group="'+groupId+'"]'), function(n,i) {
                    return !$(n).data('filtered');
                })).toggle();
            }else if(tagName == 'DD'){
                var status = $this.data('status');
                if(status == '0' || status == '3' || status == '4') {
                    $deviceList.find('dd').removeClass('on');
                    $deviceList.find('.toolbar:visible').hide();
                    $this.find('.toolbar').toggle();
                    $this.toggleClass('on');
                }
            }
        });

        $toolbar.on('click', 'input,a', function(){
            var $this = $(this),
                action = $this.data('action');
            if(action == 'refresh'){
                loadData();
            }else{
                deviceFilter(action);
            }
        });
        //静态化页面，参数需要用js解析后，手动修改各个连接地址
        $('#monitor-btn').attr('href', 'monitor.html?'+goome.wx.utils.serialize());
    }

    function init(){
        bindEvents();
        loadData();
    }

    return {
        load: init
    };
}();